package software.literature.db;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import software.literature.model.bean.BBGData;
import software.literature.model.bean.BBGRecords;

public class ReferenceDao extends DBDao {

	public ReferenceDao(String currentDB) {
		super(currentDB);
	}

	public Map<Integer, List<Integer>> queryReference() {
		Map<Integer, List<Integer>> references = new HashMap<Integer, List<Integer>>();
		try {
			getConnection();
			preStm = connection
					.prepareStatement("select * from  literature_ref_bbg");
			result = preStm.executeQuery();
			int id;
			List<Integer> list;
			while (result.next()) {
				id = result.getInt("id");
				list = references.get(id);
				if (null == list) {
					list = new ArrayList<Integer>();
					references.put(result.getInt("id"), list);
				} else {
				}
				list.add(result.getInt("ref_items_id"));
			}
			closeConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return references;
	}

	public boolean insert(int id, List<Integer> real) {
		try {
			getConnection();
			preStm = connection
					.prepareStatement("insert into   literature_ref_bbg(id,ref_items_id) values(?,?)");
			for (int i = 0; i < real.size(); i++) {
				preStm.setInt(1, id);
				preStm.setInt(2, real.get(i));
				preStm.addBatch();
			}
			connection.setAutoCommit(false);
			preStm.executeBatch();
			connection.setAutoCommit(true);
			closeConnection();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	public boolean deleteRefs(int id, List<Integer> list) {
		try {
			getConnection();
			preStm = connection.prepareStatement("delete from literature_ref_bbg where id=? and ref_items_id=?");
			for (int i = 0; i < list.size(); i++) {
				preStm.setInt(1, id);
				preStm.setInt(2, list.get(i));
				preStm.addBatch();
			}
			connection.setAutoCommit(false);
			preStm.executeBatch();
			connection.setAutoCommit(true);
			closeConnection();
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

	public boolean deleteLiteratureRefs(int id) {
		// TODO Auto-generated method stub
		try {
			getConnection();
			preStm = connection
					.prepareStatement("delete from literature_ref_bbg where ref_items_id=?");
			preStm.setInt(1, id);
			preStm.addBatch();
			connection.setAutoCommit(false);
			preStm.executeBatch();
			connection.setAutoCommit(true);
			closeConnection();
			return true;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}

}
